package artid.com.arttogoa.keeponrecord;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import artid.com.arttogoa.ElectronicSignature_Activity;
import artid.com.arttogoa.R;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.db.DataKeeper;
import artid.com.arttogoa.parser.ArtworkImageUpload;
import artid.com.arttogoa.parser.Coordinate;
import artid.com.arttogoa.parser.MicMapBean;
import artid.com.arttogoa.parser.PostionPoint;
import artid.com.arttogoa.parser.UserItem;
import artid.com.arttogoa.swipe.SwipeMenu;
import artid.com.arttogoa.swipe.SwipeMenuCreator;
import artid.com.arttogoa.swipe.SwipeMenuItem;
import artid.com.arttogoa.swipe.SwipeMenuListView;
import artid.com.arttogoa.swipe.SwipeMenuListView.OnMenuItemClickListener;
import artid.com.arttogoa.task.TouchCallback;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.ToastUtil;
import artid.com.arttogoa.view.DragImageView;
import artid.com.arttogoa.view.HView;
import artid.com.arttogoa.view.MicView;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MicroscopicMapSelectKeepActivity extends Activity implements
		OnClickListener {
	private static final String TAG = "Browse";
	private Context context;
	/** 存放标记坐标点的集合 */
	private List<PostionPoint> pointData = new ArrayList<PostionPoint>();
	/** 存放微观图的集合 */
	private ArrayList<MicMapBean> micMapList = new ArrayList<MicMapBean>();
	/** volley网络请求 */
	private RequestQueue mSingleQueue;
	/** 标题、返回键、提交键 ,上面提示信息，下面提示信息 */
	private TextView title, commit, htext, btext;
	private ImageView back;
	/** 备案缓存key（用户账号） */
	private String userPhone;
	/** 是否有缓存存在 */
	private String cacheBo;
	/** 滑动删除列表控件 */
	private SwipeMenuListView mListView;
	/** 滑动删除列表控件适配器 */
	private AppAdapter adapter;
	/** 该页面所有存在的对话框都用该对象 */
	private AlertDialog alertDialog;
	/** 控件宽度 */
	private int window_width, window_height;
	/** 展示局部高清图控件 */
	private MicView micView;
	/** 遮罩层展示红点控件 */
	private HView hView;
	/** 展示可操作图片控件 */
	private DragImageView dragImageView;
	/** 状态栏的高度 */
	private int state_height;
	/** 图片宽高 */
	private int width, height;
	/** 测量状态栏 */
	private ViewTreeObserver viewTreeObserver;
	/** 展示局部图控件方块边长 */
	public static final int micDip = 80;
	/** 获取图片参数 */
	private BitmapRegionDecoder bitmapRegionDecoder;
	private BitmapFactory.Options options;
	/** 选点按钮 */
	private ImageView btn;
	/** 微观图展示框边长 */
	private int Length;
	/** 操作图片 */
	private Bitmap bmp;
	/** 操作图片原图 */
	private Bitmap oldbmp;
	/** 备案对象 */
	private ArtworkImageUpload artwork;
	/** 按照比例得到在完整图中的坐标 */
	public double _x;
	public double _y;
	/** 圆圈画笔 */
	private Paint paint;
	/** 圈内文字画笔 */
	private Paint paintText;
	/** 以确定标注点 */
	private Bitmap b2;
	/** 备案ID */
	private String art_id;
	/** 备案上传状态 */
	private String state;
	/** 上传模式 */
	private String updataType;
	/** 当前点描述 */
	private String poiString;
	/** 局部框平移动画 */
	private ObjectAnimator left_animator, right_animator;
	/** 操作图片控件在屏幕中的top */
	private int top_dis;
	/** 局部图向右平移的x轴位置 */
	private int mic_right;
	/** 局部图左边的约束位置 */
	private int left_dis;
	/** 局部图右边的约束位置 */
	private int right_dis;
	/** 是否第一次触摸滑动 */
	private boolean ht = true;
	/** 局部图在哪边 true：左边 false：右边 */
	private boolean dis_position = true;

	// /** 是否有微观图 */
	// public static boolean micD = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.activity_mic_keep);
		ArtWorkApp.getInstance().addArtActivity(
				MicroscopicMapSelectKeepActivity.this);

		initLayout();
		initSize();
		initSwipeMenu();
		loadImage();
	}

	/** 初始化控件 */
	private void initLayout() {
		// TODO Auto-generated method stub
		context = this;

		btn = (ImageView) findViewById(R.id.btn);
		micView = (MicView) findViewById(R.id.iv_mic);
		hView = (HView) findViewById(R.id.h_v);
		dragImageView = (DragImageView) findViewById(R.id.div_main);
		htext = (TextView) findViewById(R.id.tv);
		btext = (TextView) findViewById(R.id.tv_infoo);
		title = (TextView) findViewById(R.id.title_text);
		commit = (TextView) findViewById(R.id.title_right);
		back = (ImageView) findViewById(R.id.back_btn);

		commit.setText("艺术家签名");

		micView.setVisibility(View.GONE);
		commit.setVisibility(View.VISIBLE);

		commit.setOnClickListener(this);
		back.setOnClickListener(this);
		btn.setOnClickListener(this);

		userPhone = MySharedPreferences.getMySharedPreferences(
				MicroscopicMapSelectKeepActivity.this).getValue("Phone", "");
		mSingleQueue = Volley.newRequestQueue(this);

		paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paintText = new Paint(Paint.ANTI_ALIAS_FLAG);
		paintText.setTextSize(NetUtils.dip2px(this, 10));
		paintText.setColor(Color.WHITE);
		paintText.setTextAlign(Paint.Align.CENTER);
		paintText.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));

		/** 初始化备案模式 **/
		updataType = MySharedPreferences.getMySharedPreferences(
				MicroscopicMapSelectKeepActivity.this).getValue(Cache.ART_TYPE,
				"");

		/** 添加监听home键广播 **/
		registerReceiver(mHomeKeyEventReceiver, new IntentFilter(
				Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

		/** 初始化标题标志 **/
		Drawable drawable = null;
		if (updataType.equals(ArtRecordActivity._PHONE)) {
			poiString = "局部特征图";
			drawable = getResources().getDrawable(R.drawable.a_ico_iphone);
		} else if (updataType.equals(ArtRecordActivity._FILING)) {
			poiString = "微观特征点";
			drawable = getResources().getDrawable(R.drawable.a_ico_shebei);
		}
		title.setText(poiString);
		htext.setText("通过两指可进行图片缩放,点击\"对勾\"确定" + poiString + "位置。");
		btext.setText("当前还没有选取" + poiString + "，请点击取点");
		// / 这一步必须要做,否则不会显示.
		drawable.setBounds(0, 0, drawable.getMinimumWidth(),
				drawable.getMinimumHeight());
		title.setCompoundDrawablePadding(20);
		title.setCompoundDrawables(drawable, null, null, null);
		setSelect(false);
	}

	/** 初始化尺寸 **/
	private void initSize() {
		// TODO Auto-generated method stub
		Length = NetUtils.dip2px(this, micDip);
		// String size = MySharedPreferences.getMySharedPreferences(
		// MicroscopicMapSelectKeepActivity.this).getValue(Cache.ART_SIZE,
		// "");
		// if (!TextUtils.isEmpty(size)) {
		// dragImageView.setScreen_H(window_height
		// - state_height);
		// dragImageView.setScreen_W(window_width);
		// } else {
		window_width = Integer.valueOf(NetUtils.getDisplayMetrics(this).get(
				NetUtils.DM_WIDTH));
		window_height = Integer.valueOf(NetUtils.getDisplayMetrics(this).get(
				NetUtils.DM_HEIGHT));
		/** 初始化约束 */
		mic_right = window_width - (NetUtils.dip2px(this, 20) + Length);
		left_dis = NetUtils.dip2px(this, 10) + Length;
		right_dis = NetUtils.dip2px(this, 10) + mic_right;
		/** 从左到右 */
		left_animator = ObjectAnimator.ofFloat(micView, "translationX", 0,
				mic_right).setDuration(300);
		/** 从右到左 */
		right_animator = ObjectAnimator.ofFloat(micView, "translationX",
				mic_right, 0).setDuration(300);
		// left_animator.addListener(listenter);
		// left_animator.addListener(listenter);
		/** 初始化尺寸 */
		dragImageView.setmActivity(this);// 注入Activity.
		dragImageView.setTouchCallback(touchCallback);// 添加触摸回调
		// System.out.println(bmp.getWidth() + "," + bmp.getHeight() + ","
		// + window_height + "," + window_width);
		dragImageView.setScreen_H(NetUtils.dip2px(
				MicroscopicMapSelectKeepActivity.this, 350));
		dragImageView.setScreen_W(window_width);

		/** 测量状态栏高度 **/
		viewTreeObserver = dragImageView.getViewTreeObserver();
		viewTreeObserver
				.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
					@Override
					public void onGlobalLayout() {
						if (state_height == 0) {
							// 获取状况栏高度
							Rect frame = new Rect();
							getWindow().getDecorView()
									.getWindowVisibleDisplayFrame(frame);
							state_height = frame.top;
							window_height = window_height - state_height;
						}
					}
				});
		int infoHeight = NetUtils.dip2px(context, 44 + 45);
		int listHeight = NetUtils.dip2px(context, 87);
		/** 最终的高度为：屏幕高度-状态栏高度-提示文字高度-列表高度 */
		window_height = window_height - infoHeight - listHeight;
		MySharedPreferences.getMySharedPreferences(
				MicroscopicMapSelectKeepActivity.this).setValue(Cache.ART_SIZE,
				String.valueOf(window_height));
		// }

	}

	/** 初始化图片展示相关控件及对象 **/
	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	private void loadImage() {
		// TODO Auto-generated method stub
		artwork = (ArtworkImageUpload) DataKeeper
				.readSerializable(MicroscopicMapSelectKeepActivity.this,
						ArtworkImageUpload.class);
		AlertUtils.initloadAlertDialog(MicroscopicMapSelectKeepActivity.this,
				MicroscopicMapSelectKeepActivity.this.getWindowManager()
						.getDefaultDisplay().getWidth(), "正在加载完整图...");

		Glide.with(MicroscopicMapSelectKeepActivity.this)
				.load(artwork.getImgdata()).asBitmap()
				.diskCacheStrategy(DiskCacheStrategy.NONE)
				.into(new SimpleTarget<Bitmap>() {
					@SuppressLint("NewApi")
					@Override
					public void onResourceReady(Bitmap resource,
							GlideAnimation<? super Bitmap> glideAnimation) {
						AlertUtils.dismiss();
						try {
							// 获得图片的宽、高
							BitmapFactory.Options Options = new BitmapFactory.Options();
							/**
							 * 最关键在此，把options.inJustDecodeBounds = true;
							 * 这里再decodeFile()，返回的bitmap为空
							 * ，但此时调用options.outHeight时，已经包含了图片的高了
							 */
							Options.inJustDecodeBounds = true;
							Bitmap bitmap1 = BitmapFactory.decodeFile(
									artwork.getImgdata(), Options); // 此时返回的bitmap为null
							width = Options.outWidth;
							height = Options.outHeight;

							InputStream isBm = new FileInputStream(artwork
									.getImgdata());
							// 设置显示图片的区域参数
							bitmapRegionDecoder = BitmapRegionDecoder
									.newInstance(isBm, false);
							options = new BitmapFactory.Options();
							options.inPreferredConfig = Bitmap.Config.RGB_565;
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						bmp = BitmapUtil.getBitmap(resource, window_width,
								NetUtils.dip2px(
										MicroscopicMapSelectKeepActivity.this,
										350));
						// bmp = BitmapUtil.getBitmap(resource, window_width,
						// window_height);
						System.out.println(bmp.getWidth() + "="
								+ bmp.getHeight());
						oldbmp = bmp;
						initCache();
					}
				});

	}

	/** 加载图片 **/
	private void initImage(Bitmap bmp) {
		// TODO Auto-generated method stub
		dragImageView.setImageBitmap(bmp);

		if (micMapList.size() < 1) {
			btext.setText("当前还没有选取" + poiString + "，请点击取点");
		} else {
			btext.setText("");
		}
	}

	/** 图片限制：0，无限制 1，只能选手机局部图 2，只能选200倍微观图 3,不能再选图 */
	private int pictureLimit = 0;
	int i = 0;// 微观图数
	int j = 0;// 局部图数

	public void setPictureLimit() {
		i = 0;
		j = 0;
		if (micMapList.size() > 0) {
			for (int z = 0; z < micMapList.size(); z++) {
				MicMapBean mic = micMapList.get(z);
				boolean lim = mic.isArtMictype();
				System.out.println("isArtMictype=" + lim);
				if (lim)
					i++;
				else
					j++;
			}
			System.out.println("i=" + i + ",j=" + j);
			if (i > 2 && j < 3)
				pictureLimit = 1;
			else if (j > 2 && i < 3)
				pictureLimit = 2;
			else if (j > 2 && i > 2)
				pictureLimit = 3;
			else
				pictureLimit = 0;
		} else {
			pictureLimit = 0;
		}

	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		/** 点击艺术家签名 */
		case R.id.title_right:
			if (commit.getText().toString().trim().equals("艺术家签名")) {
				Intent intent = new Intent(
						MicroscopicMapSelectKeepActivity.this,
						ElectronicSignature_Activity.class);
				startActivityForResult(intent, 1);

			} else if (commit.getText().toString().trim().equals("提交备案")) {
				setPictureLimit();
				/** wifi SD卡 名字 */
				String ezssid = MySharedPreferences.getMySharedPreferences(
						context).getValue(MySharedPreferences.EZSHARE_WIFI, "");
				if (!NetUtils.isNetworkConnected(context)) {
					AlertUtils.initSubmitSumAlertDialog(
							MicroscopicMapSelectKeepActivity.this, "当前网络不可用");
					return;
				}
				/** 判断当前网络状态 */
				if (!TextUtils.isEmpty(ezssid)
						&& NetUtils.getSSID(
								MicroscopicMapSelectKeepActivity.this).equals(
								ezssid)) {
					AlertUtils
							.initJudgeOutsideAlertDialog(MicroscopicMapSelectKeepActivity.this);
					return;
				} else if (updataType.equals(ArtRecordActivity._FILING)
						&& micMapList.size() < 3) {
					AlertUtils.initSubmitSumAlertDialog(
							MicroscopicMapSelectKeepActivity.this, "需要取3个点");
					return;
				} else if (updataType.equals(ArtRecordActivity._PHONE) && j < 3) {
					AlertUtils
							.initSubmitSumAlertDialog(
									MicroscopicMapSelectKeepActivity.this,
									"至少需要取3个局部图");
					return;
				}
				resetURL();
				storageCache();
				if (i > 0) {
					checkSdCard();
				} else {
					AlertUtils.initUploadAlertDialog(
							MicroscopicMapSelectKeepActivity.this,
							MicroscopicMapSelectKeepActivity.this
									.getWindowManager().getDefaultDisplay()
									.getWidth(), "正在上传合影及完整图");
					new Thread(networkTask).start();
				}
			}

			break;

		case R.id.btn:
			if (updataType.equals(ArtRecordActivity._PHONE)) {
				setPictureLimit();
				if (pictureLimit == 3) {
					Toast.makeText(MicroscopicMapSelectKeepActivity.this,
							"选择的" + poiString + "已到上限", 2).show();
					return;
				}

			} else if (updataType.equals(ArtRecordActivity._FILING)) {
				if (micMapList.size() < 3)
					pictureLimit = 0;
				else {
					Toast.makeText(MicroscopicMapSelectKeepActivity.this,
							"选择的" + poiString + "已到上限", 2).show();
					pictureLimit = 3;
					return;
				}
			}
			MicMapBean mic = new MicMapBean();
			mic.setPf(new PostionPoint((int) _x, (int) _y));
			mic.setId(pointData.size());
			Intent intent = new Intent(MicroscopicMapSelectKeepActivity.this,
					MicroscopicMapInfoActivity.class);
			Bundle b = new Bundle();
			b.putSerializable("data", mic);
			b.putInt("pictureLimit", pictureLimit);
			intent.putExtras(b);
			startActivityForResult(intent, 1);
			break;
		case R.id.back_btn:
			finish();
			break;
		default:
			break;
		}
	}

	private String urlcom;
	private String urlmic;
	private String urlcomplete;

	private void resetURL() {
		// TODO Auto-generated method stub
		if (updataType.equals(ArtRecordActivity._PHONE)) {
			urlcom = Cache.upload_p;
			urlmic = Cache.uploadMicrogram_p;
			urlcomplete = Cache.saveartRecord_P;
		} else if (updataType.equals(ArtRecordActivity._FILING)) {
			urlcom = Cache.upload;
			urlmic = Cache.uploadMicrogram;
			urlcomplete = Cache.saveartRecord;
		}
	}

	/** 在完整图上画一个点 */
	private void getBitmap(double x, double y, boolean b) {
		// TODO Auto-generated method stub
		if (b)
			b2 = BitmapFactory.decodeResource(getResources(),
					R.drawable.ico_toumingread);
		else
			b2 = BitmapFactory.decodeResource(getResources(),
					R.drawable.ico_gangread);
		x = (double) bmp.getWidth() / (double) width * x;
		y = (double) bmp.getHeight() / (double) height * y;
		Canvas canvas = new Canvas(bmp);
		canvas.drawBitmap(b2, (int) (x - b2.getWidth() / 2),
				(int) (y - b2.getWidth() / 2), paint);
		canvas.drawText(String.valueOf(pointData.size()), (int) x,
				(int) (y + NetUtils.dip2px(this, 3)), paintText);
	}

	/** 在完整图上画多个点 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
	@SuppressLint("NewApi")
	private void getBitmapSize(ArrayList<MicMapBean> data, boolean b) {
		// TODO Auto-generated method stub
		System.out.println("oldbmp=" + oldbmp.getByteCount());
		System.out.println("bmp=" + bmp.getByteCount());
		/** 判断如果是删除，就重新标点=重新为操作图片赋值 */
		Canvas canvas;
		if (b) {
			bmp = null;
			bmp = oldbmp;
		}
		/** 填充画布 */
		canvas = new Canvas(bmp);

		for (int i = 0; i < data.size(); i++) {
			PostionPoint p = data.get(i).getPf();
			double x = (double) bmp.getWidth() / (double) width * p.getPointX();
			double y = (double) bmp.getHeight() / (double) height
					* p.getPointY();
			if (data.get(i).isArtMictype())
				b2 = BitmapFactory.decodeResource(getResources(),
						R.drawable.ico_toumingread);
			else
				b2 = BitmapFactory.decodeResource(getResources(),
						R.drawable.ico_gangread);
			canvas.drawBitmap(b2, (int) (x - b2.getWidth() / 2),
					(int) (y - b2.getWidth() / 2), paint);
			canvas.drawText(String.valueOf(i + 1), (int) x,
					(int) (y + NetUtils.dip2px(this, 3)), paintText);
		}

	}

	/** 设置选点按钮图片 */
	private void setSelect(boolean no) {
		// TODO Auto-generated method stub
		if (no) {
			btn.setImageResource(R.drawable.ok2x);
		} else {
			btn.setImageResource(R.drawable.grey2x);
		}
	}

	/** 给自定义图片控件添加触摸事件 */
	private TouchCallback touchCallback = new TouchCallback() {

		@Override
		public void releaseCallBack2() {
			// TODO Auto-generated method stub
			// micView.setVisibility(View.GONE);
		}

		@Override
		public void releaseCallBack() {
			// TODO Auto-generated method stub
			System.out.println("releaseCallBack回调");
			hView.rePainting();
		}

		@SuppressLint("NewApi")
		@Override
		public void pressCallBack(Coordinate coo) {
			// TODO Auto-generated method stub
			if (ht) {
				int[] location = new int[2];
				dragImageView.getLocationOnScreen(location);
				int x = location[0];
				int y = location[1];
				System.out.println("x:" + x + "y:" + y);
				top_dis = y;

				ht = false;
			}
			// System.out.println("控件中距顶端=" + (coo.y1 - top_dis));
			if (coo.x1 > dragImageView.getLeft()
					&& coo.x1 < dragImageView.getRight()) {
				hView.setPainting((int) coo.x1, (int) (coo.y1 - top_dis));
			} else {
				hView.rePainting();
			}
			System.out.println("图片各个角Left：" + micView.getLeft() + "Right："
					+ micView.getRight() + "Top：" + micView.getTop()
					+ "Bottom：" + micView.getBottom());
			if (dis_position
					&& coo.x1 < left_dis
					&& coo.y1 < (micView.getBottom() + state_height + NetUtils
							.dip2px(MicroscopicMapSelectKeepActivity.this, 44))) {
				dis_position = false;
				left_animator.start();
			} else if (!dis_position
					&& coo.x1 > right_dis
					&& coo.y1 < (micView.getBottom() + state_height + NetUtils
							.dip2px(MicroscopicMapSelectKeepActivity.this, 44))) {
				dis_position = true;
				right_animator.start();
			}
			// 得到同比例完整图坐标
			_x = (double) width / (double) coo.width * coo.x;
			_y = (double) height / (double) coo.height * coo.y;
			// System.out.println("pressCallBack回调,x=" + _x + ",y=" + _y
			// + ",width=" + width + ",height=" + height);
			// 微观图矩阵坐标
			int left = (int) (_x - Length / 2);
			int top = (int) (_y - Length / 2);
			int right = (int) (_x + Length / 2);
			int bottom = (int) (_y + Length / 2);
			// 微观图红圆点坐标
			int circleX = Length / 2;
			int circleY = Length / 2;
			// 控制微观图边界
			if (left <= 0) {
				circleX = (int) _x;
				left = 0;
				right = Length;
			}
			if (top <= 0) {
				circleY = (int) _y;
				top = 0;
				bottom = Length;
			}
			if (right >= width) {
				circleX = (int) (Length - (width - _x));
				right = width;
				left = width - Length;
			}
			if (bottom >= height) {
				circleY = (int) (Length - (height - _y));
				bottom = height;
				top = height - Length;
			}
			// 判断红点出界,出界则隐藏
			if (circleX < 0 || circleX > Length || circleY < 0
					|| circleY > Length) {
				micView.setVisibility(View.GONE);
				setSelect(false);
			} else {
				micView.setVisibility(View.VISIBLE);
				setSelect(true);
			}
			// 控制微观图红圆点坐标
			// 暂时不用控制
			System.out.println(left + "," + top + "," + right + "," + bottom);

			// System.out.println(bitmapRegionDecoder.getHeight() + ","
			// + bitmapRegionDecoder.getWidth());
			Bitmap bitmap = bitmapRegionDecoder.decodeRegion(new Rect(left,
					top, right, bottom), options);
			micView.setToUpdate(bitmap, circleX, circleY);
		}
	};
	/**
	 * 监听是否点击了home键将客户端推到后台
	 */
	private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
		String SYSTEM_REASON = "reason";
		String SYSTEM_HOME_KEY = "homekey";
		String SYSTEM_HOME_KEY_LONG = "recentapps";

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
				String reason = intent.getStringExtra(SYSTEM_REASON);
				if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
					// 表示按了home键,程序到了后台
					storageCache();
				} else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
					// 表示长按home键,显示最近使用的程序列表
					storageCache();
				}
			}
		}
	};

	/**
	 * 初始化备案缓存
	 */
	void initCache() {

		cacheBo = MySharedPreferences.getMySharedPreferences(
				MicroscopicMapSelectKeepActivity.this).getValue(
				Cache.IS_CACHE + userPhone, "false");
		if (Boolean.valueOf(cacheBo)) {
			String cache = MySharedPreferences.getMySharedPreferences(
					MicroscopicMapSelectKeepActivity.this).getValue(
					Cache.ART_CACHE + userPhone, "");
			try {
				JSONObject ob = new JSONObject(cache);
				JSONArray jaa = ob.optJSONArray("micMapList");
				System.out.println(ob.toString());
				if (jaa != null && jaa.length() > 0) {

					for (int i = 0; i < jaa.length(); i++) {
						JSONObject mic = jaa.optJSONObject(i);
						MicMapBean mb = new MicMapBean();
						String microgramdata = mic.optString("microgramdata");
						if (!TextUtils.isEmpty(microgramdata)) {
							mb.setImage(microgramdata);
						}
						String microgramdatamax = mic
								.optString("microgramdatamax");
						if (!TextUtils.isEmpty(microgramdatamax)) {
							mb.setImage200(microgramdatamax);
						}
						String xcoordinate = mic.optString("xcoordinate");
						String ycoordinate = mic.optString("ycoordinate");
						if (!TextUtils.isEmpty(xcoordinate)
								&& !TextUtils.isEmpty(ycoordinate)) {
							mb.setPf(new PostionPoint(Integer
									.parseInt(xcoordinate), Integer
									.parseInt(ycoordinate)));
						}
						String microgram_detail = mic
								.optString("microgram_detail");
						if (!TextUtils.isEmpty(microgram_detail)) {
							mb.setInfo(microgram_detail);
						}
						String mictype = mic.optString("mictype");
						if (!TextUtils.isEmpty(mictype)) {
							mb.setArtMictype(Boolean.valueOf(mictype));
						}
						micMapList.add(mb);
						pointData.add(new PostionPoint(mb.getPf().getPointX(),
								mb.getPf().getPointY()));
						getBitmapSize(micMapList, false);
					}
					initImage(bmp);
				} else {
					initImage(bmp);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// adapter.setListData(micMapList);
			// bv.setInitPointData(bmp, mapCenter, screenCenter, pointData);
		} else {
			initImage(bmp);
		}
	}

	/**
	 * 添加备案缓存
	 */
	void storageCache() {
		String cache = MySharedPreferences.getMySharedPreferences(
				MicroscopicMapSelectKeepActivity.this).getValue(
				Cache.ART_CACHE + userPhone, "");
		System.out.println("storageCache=" + cache);
		try {
			JSONObject ob = new JSONObject(cache);
			JSONArray arr = new JSONArray();
			for (int i = 0; i < micMapList.size(); i++) {
				JSONObject mic = new JSONObject();
				MicMapBean mb = micMapList.get(i);
				String microgramdata = mb.getImage();
				if (!TextUtils.isEmpty(microgramdata)) {
					mic.put("microgramdata", microgramdata);
				}
				String microgramdatamax = mb.getImage200();
				if (!TextUtils.isEmpty(microgramdatamax)) {
					mic.put("microgramdatamax", microgramdatamax);
				}
				String mictype = String.valueOf(mb.isArtMictype());
				if (!TextUtils.isEmpty(mictype)) {
					mic.put("mictype", mictype);
				}
				String xcoordinate = String.valueOf(mb.getPf().getPointX());
				if (!TextUtils.isEmpty(xcoordinate)) {
					mic.put("xcoordinate", xcoordinate);
				}
				String ycoordinate = String.valueOf(mb.getPf().getPointY());
				if (!TextUtils.isEmpty(ycoordinate)) {
					mic.put("ycoordinate", ycoordinate);
				}
				String microgram_detail = mb.getInfo();
				if (!TextUtils.isEmpty(microgram_detail)) {
					mic.put("microgram_detail", microgram_detail);
				}
				arr.put(mic);
			}
			ob.put("micMapList", arr);
			System.out.println("storageCache=" + ob.toString());
			MySharedPreferences.getMySharedPreferences(
					MicroscopicMapSelectKeepActivity.this).setValue(
					Cache.ART_CACHE + userPhone, ob.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/** 在页面关闭时缓存页面数据 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		storageCache();
		super.onDestroy();
	}

	/** 初始化微观图列表 */
	private void initSwipeMenu() {
		// TODO Auto-generated method stub
		//
		mListView = (SwipeMenuListView) findViewById(R.id.listView);
		adapter = new AppAdapter(micMapList);
		mListView.setAdapter(adapter);
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "delete" item
				SwipeMenuItem deleteItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
						0x3F, 0x25)));
				// set item width
				deleteItem.setWidth(NetUtils.dip2px(context, 75));
				// set a icon
				deleteItem.setIcon(R.drawable.ic_delete);
				// add to menu
				menu.addMenuItem(deleteItem);
			}
		};
		// set creator
		mListView.setMenuCreator(creator);

		// step 2. listener item click event
		mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu,
					int index) {
				switch (index) {
				case 0:
					micMapList.remove(position);
					pointData.remove(position);
					adapter.setListData(micMapList);
					getBitmapSize(micMapList, true);
					initImage(bmp);
					break;
				}
				return false;
			}
		});
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,
					long arg3) {
				Intent intent = new Intent(
						MicroscopicMapSelectKeepActivity.this,
						MicroscopicMapBrowseActivity.class);
				Bundle b = new Bundle();
				b.putSerializable("data", micMapList);
				b.putInt("pictureLimit", pictureLimit);
				b.putInt("index", index);
				intent.putExtras(b);
				startActivityForResult(intent, 2);
			}
		});
	}

	class AppAdapter extends BaseAdapter {
		private ArrayList<MicMapBean> data;

		/**
		 * 
		 */
		public AppAdapter(ArrayList<MicMapBean> data) {
			// TODO Auto-generated constructor stub
			this.data = data;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		public void setListData(ArrayList<MicMapBean> data) {
			this.data = data;
			notifyDataSetChanged();
		}

		@Override
		public MicMapBean getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(getApplicationContext(),
						R.layout.item_microcosmic_list, null);
				new ViewHolder(convertView);
			}
			ViewHolder holder = (ViewHolder) convertView.getTag();
			holder.index.setText((position + 1) + "");
			MicMapBean mic = data.get(position);
			if (mic.getInfo() != null)
				holder.content.setText(mic.getInfo());
			if (updataType.equals(ArtRecordActivity._PHONE)) {
				holder.image200.setVisibility(View.GONE);
				holder.text200.setVisibility(View.GONE);
				if (mic.isArtMictype()) {
					holder.ib_index.setImageResource(R.drawable.ico_quanquan);
					holder.utext.setText("200倍");
				} else {
					holder.ib_index.setImageResource(R.drawable.smjg_ico_fang);
					holder.utext.setText("局部图");
				}
				Glide.with(MicroscopicMapSelectKeepActivity.this)
						.load(new File(mic.getImage()))
						.placeholder(R.drawable.yspba_img_mor)
						.error(R.drawable.yspba_img_mor).into(holder.image);
			} else if (updataType.equals(ArtRecordActivity._FILING)) {
				Glide.with(MicroscopicMapSelectKeepActivity.this)
						.load(new File(mic.getImage()))
						.placeholder(R.drawable.yspba_img_mor)
						.error(R.drawable.yspba_img_mor).into(holder.image);
				Glide.with(MicroscopicMapSelectKeepActivity.this)
						.load(new File(mic.getImage200()))
						.placeholder(R.drawable.yspba_img_mor)
						.error(R.drawable.yspba_img_mor).into(holder.image200);
			}

			// holder.image.setImageBitmap(getLoacalBitmap(mic.getImage()));

			return convertView;
		}

		class ViewHolder {
			TextView index, content, text200, utext;
			ImageView image, image200, ib_index;

			public ViewHolder(View view) {
				content = (TextView) view.findViewById(R.id.tv_content);
				utext = (TextView) view.findViewById(R.id.tv_uinfo);
				index = (TextView) view.findViewById(R.id.tv_index);
				text200 = (TextView) view.findViewById(R.id.iv_text_200);
				image = (ImageView) view.findViewById(R.id.iv_mic);
				ib_index = (ImageView) view.findViewById(R.id.ib_index);
				image200 = (ImageView) view.findViewById(R.id.iv_mic_200);
				view.setTag(this);
			}
		}
	}

	/** 艺术家签名路径 */
	private String Electpath;

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (resultCode) {
		/** 从选择微观图页面跳回德尔 */
		case 9:
			MicMapBean mic = (MicMapBean) data.getExtras().getSerializable(
					"data");
			micMapList.add(mic);
			pointData.add(mic.getPf());
			adapter.setListData(micMapList);
			getBitmap(mic.getPf().getPointX(), mic.getPf().getPointY(),
					mic.isArtMictype());
			initImage(bmp);
			break;
		/** 从浏览微观图页面跳回德尔 */
		case 10:
			// NewActivity的返回数据
			micMapList = (ArrayList<MicMapBean>) data.getExtras()
					.getSerializable("data");
			adapter.setListData(micMapList);
			break;
		/** 从艺术家签名跳回 */
		case 8:
			Electpath = Environment.getExternalStorageDirectory()
					+ "/YJB/handwritingBoard.png";
			commit.setText("提交备案");
			break;
		default:
			break;
		}

	}

	/**
	 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!---网络请求---!!!!!!!!!
	 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	 */

	private void checkSdCard() {
		String mac = MySharedPreferences.getMySharedPreferences(context)
				.getValue("mac", "");
		VolleyBasic.getInstance(MicroscopicMapSelectKeepActivity.this).post(
				false, false, Cache.checkSdCard,
				VolleyMap.getInstance().checkSdCard(mac), UserItem.class,
				new VolleyCallback() {
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						// System.out.println("第一个============" + vd.getJson());
						UserItem us = (UserItem) vd.getData();
						JSONObject jo = null;
						try {
							jo = new JSONObject(vd.getJson());
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						int state = Integer.parseInt(jo.optJSONObject("data")
								.optString("state"));
						switch (state) {
						case 3:
							AlertUtils.initUploadAlertDialog(
									MicroscopicMapSelectKeepActivity.this,
									MicroscopicMapSelectKeepActivity.this
											.getWindowManager()
											.getDefaultDisplay().getWidth(),
									"正在上传合影及完整图");
							new Thread(networkTask).start();
							break;
						case 1:
						case 2:
							AlertUtils.initSubmitSumAlertDialog(
									MicroscopicMapSelectKeepActivity.this,
									vd.getMsg());
							break;
						case 4:
							AlertUtils.AlertTwoBtnDialog(context, vd.getMsg(),
									"确定", "取消",
									MicroscopicMapSelectKeepActivity.this
											.getWindowManager()
											.getDefaultDisplay().getWidth(),
									new OnClickListener() {

										@Override
										public void onClick(View v) {
											// TODO Auto-generated method stub
											switch (v.getId()) {
											case R.id.tv_ok:
												bindSdCard();
												AlertUtils.dismiss();
												break;
											case R.id.tv_no:
												AlertUtils.dismiss();
												break;

											default:
												break;
											}
										}
									});
							break;
						default:
							break;
						}
					}

					public void onError(VolleyError volleyError) {
						AlertUtils.dismiss();
					}
				});
	}

	private void bindSdCard() {
		String mac = MySharedPreferences.getMySharedPreferences(context)
				.getValue("mac", "");
		VolleyBasic.getInstance(MicroscopicMapSelectKeepActivity.this).post(
				true, true, Cache.bindSdCard,
				VolleyMap.getInstance().checkSdCard(mac), UserItem.class,
				new VolleyCallback() {
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						// System.out.println("第一个============" + vd.getJson());
						UserItem us = (UserItem) vd.getData();
						JSONObject jo = null;
						try {
							jo = new JSONObject(vd.getJson());
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						int state = Integer.parseInt(jo.optJSONObject("data")
								.optString("state"));
						switch (state) {
						case 0:
							AlertUtils.initUploadAlertDialog(
									MicroscopicMapSelectKeepActivity.this,
									MicroscopicMapSelectKeepActivity.this
											.getWindowManager()
											.getDefaultDisplay().getWidth(),
									"正在上传合影及完整图");
							new Thread(networkTask).start();
							break;
						case 1:
							Toast.makeText(context, vd.getMsg(), 2).show();
							break;
						default:
							break;
						}
					}

					public void onError(VolleyError volleyError) {
						AlertUtils.dismiss();
					}
				});
	}

	private final int TYPE_COM = 1;
	private final int TYPE_MIC = 2;
	private final int TYPE_WANCHENG = 3;
	private long imageIengh;
	/**
	 * 上传合影完整图
	 */
	Runnable networkTask = new Runnable() {

		@Override
		public void run() {
			// TODO
			// 在这里进行 http request.网络请求相关操作
			// String uri = Cache.upload;
			Map<String, String> params = new HashMap<String, String>();
			params.put("token", AppUtil.getUser().getToken());
			params.put("art_type", "1");
			params.put("is_file", "2");
			params.put("title", artwork.getTitle());
			params.put("realname", artwork.getRealname());
			params.put("width", artwork.getWidth());
			params.put("height", artwork.getHeight());
			params.put("age", artwork.getAge());
			params.put("detail", artwork.getDetail());
			params.put("gphoto_detail", artwork.getGphoto_detail());
			Map<String, File> files = new HashMap<String, File>();
			if (updataType.equals(ArtRecordActivity._PHONE)) {
				files.put("artist_signature",
						new File(Environment.getExternalStorageDirectory()
								+ "/YJB/handwritingBoard.png"));
			}
			files.put("gphotodata", new File(artwork.getGphotodata()));
			files.put("imgdata", new File(artwork.getImgdata()));
			files.put("inscribeimg", new File(artwork.getInscribeimg()));
			imageIengh = artwork.getLengh();
			try {
				String Response = post(urlcom, params, files, TYPE_COM, -1);
				if (TextUtils.isEmpty(Response)) {
					Message m = new Message();
					m.what = -1;
					handler.sendMessage(m);
					return;
				}
				Message msg = new Message();
				Bundle data = new Bundle();
				data.putString("value", Response);
				data.putInt("type", TYPE_COM);
				msg.setData(data);
				msg.what = 1;
				handler.sendMessage(msg);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	};
	/**
	 * 上传微观图
	 */
	Runnable micNetworkTask = new Runnable() {

		@Override
		public void run() {
			// TODO
			// 在这里进行 http request.网络请求相关操作
			for (int i = 0; i < micMapList.size(); i++) {
				MicMapBean mb = micMapList.get(i);
				Map<String, File> files = new HashMap<String, File>();

				files.put("microgramdata", new File(mb.getImage()));
				if (updataType.equals(ArtRecordActivity._FILING)) {
					files.put("microgramdatamax", new File(mb.getImage200()));
				}

				Map<String, String> params = new HashMap<String, String>();
				params.put("token", AppUtil.getUser().getToken());
				params.put("art_id", art_id);
				params.put("is_file", "2");
				params.put("imgtype", mb.getImgtype());
				params.put("number", (i + 1) + "");
				params.put("microgram_detail", mb.getInfo());
				params.put("xcoordinate", mb.getPf().getPointX() + "");
				params.put("ycoordinate", mb.getPf().getPointY() + "");
				if (updataType.equals(ArtRecordActivity._PHONE)) {
					params.put("picture_source", mb.isArtMictype() ? "2" : "1");
				}
				// String uri = Cache.uploadMicrogram;
				try {
					String Response = post(urlmic, params, files, TYPE_MIC, i);
					if (TextUtils.isEmpty(Response)) {
						Message m = new Message();
						m.what = -1;
						handler.sendMessage(m);
						break;
					}
					Message msg = new Message();
					Bundle data = new Bundle();
					data.putString("value", Response);
					data.putInt("type", TYPE_MIC);
					data.putInt("index", i);
					msg.setData(data);
					msg.what = 1;
					handler.sendMessage(msg);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}
	};

	/**
	 * 完成
	 */
	Runnable comNetworkTask = new Runnable() {

		@Override
		public void run() {
			// TODO
			// 在这里进行 http request.网络请求相关操作
			// String uri = Cache.saveartRecord;
			Map<String, String> params = new HashMap<String, String>();
			params.put("token", AppUtil.getUser().getToken());
			params.put("art_id", art_id);
			System.out.println("urlcomplete=" + urlcomplete);
			System.out.println("params=" + params.toString());
			try {
				String Response = post(urlcomplete, params, null,
						TYPE_WANCHENG, -1);
				Message msg = new Message();
				Bundle data = new Bundle();
				data.putString("value", Response);
				data.putInt("type", TYPE_WANCHENG);
				msg.setData(data);
				msg.what = 3;
				handler.sendMessage(msg);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	};

	public String post(String url, Map<String, String> params,
			Map<String, File> files, int type, int index) throws IOException {
		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";
		URL uri = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(120 * 1000); // 缓存的最长时间
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false); // 不允许使用缓存
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Accept",
				"application/json, text/javascript, */*");
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);
		conn.setChunkedStreamingMode(1024);
		// 首先组拼文本类型的参数
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + LINEND);
			// sb.append("Content-Type: text/plain; charset=" + CHARSET +
			// LINEND);
			// sb.append("Content-Transfer-Encoding: utf-8" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
		}
		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());

		outStream.write(sb.toString().getBytes());
		// 发送文件数据
		int length = 0;
		if (files != null)
			for (Map.Entry<String, File> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\""
						+ file.getKey() + "\"; filename=\""
						+ file.getValue().getName() + "\"" + LINEND);
				// sb1.append("Content-Type: application/octet-stream; charset="
				// + CHARSET + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());

				InputStream is = new FileInputStream(file.getValue());
				long total = is.available();
				System.out.println("图片的data大小==============" + total);
				byte[] buffer = new byte[1024];
				int len = 0;

				while ((len = is.read(buffer)) != -1) {

					outStream.write(buffer, 0, len);
					length += len;
					if (type == TYPE_COM) {
						Message msg = new Message();
						msg.what = 2;
						msg.obj = (int) ((length / (float) imageIengh) * 100);
						handler.sendMessage(msg);
					} else if (type == TYPE_MIC) {
						Message msg = new Message();
						msg.what = 2;
						msg.obj = (int) ((length / (float) total) * 100);
						handler.sendMessage(msg);
					}
				}
				is.close();
				outStream.write(LINEND.getBytes());

			}
		System.out.println(outStream.toString());
		// 请求结束标志
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();
		// 得到响应码
		StringBuilder sb2 = null;
		try {
			int res = conn.getResponseCode();
			InputStream in = conn.getInputStream();
			sb2 = new StringBuilder();
			if (res == 200) {
				int ch;
				while ((ch = in.read()) != -1) {
					sb2.append((char) ch);
				}
			}
		} catch (SocketTimeoutException e) {
			// TODO: handle exception
			e.printStackTrace();

			return "";
		}

		outStream.close();
		conn.disconnect();
		return sb2.toString();
	}

	/**
	 * 确认提交申请备案
	 */
	private void comNetwork() {

		// TODO Auto-generated method stub
		String uri = Cache.saveartRecord;
		// System.out.println("params=" + params.toString());

		VolleyBasic.getInstance(MicroscopicMapSelectKeepActivity.this).post(
				false, false, uri,
				VolleyMap.getInstance().saveartRecord(art_id), UserItem.class,
				new VolleyCallback() {
					public void onSuccess(VolleyData vd) {
						AlertUtils.dismiss();
						// TODO
						// Auto-generated
						// method stub
						Log.i("my上传3", "请求结果3为-->" + vd.getJson());
						try {
							JSONObject jo = new JSONObject(vd.getJson());
							if (jo.optString("ret").equals("1")) {
								// String
								// state
								// =
								// jo.optJSONObject("data").optString(
								// "state");

								MySharedPreferences.getMySharedPreferences(
										context).setValue(Cache.artIsLoad,
										"yes");
								Toast.makeText(
										MicroscopicMapSelectKeepActivity.this,
										"上传成功！", 2).show();
								ArtWorkApp.getInstance().artExit();
							} else {
								Toast.makeText(
										MicroscopicMapSelectKeepActivity.this,
										jo.optString("msg") + " ", 2).show();
							}

						} catch (JSONException e) {
							// TODO
							// Auto-generated
							// catch
							// block
							e.printStackTrace();
						}
					}

					public void onError(VolleyError volleyError) {
						AlertUtils.dismiss();
					}
				});
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				Bundle data = msg.getData();
				String val = data.getString("value");
				int type = data.getInt("type");
				if (!TextUtils.isEmpty(val)) {
					val = val.substring(val.indexOf("{"),
							val.lastIndexOf("}") + 1);
					val = NetUtils.decodeUnicode(val);
					Log.i("mylog", "请求结果为-->" + val);
					try {
						JSONObject jo = new JSONObject(val);
						if (jo.optString("ret").equals("1")) {
							if (type == TYPE_COM) {
								state = jo.optJSONObject("data").optString(
										"state");
								art_id = jo.optJSONObject("data").optString(
										"art_id");
								Log.e("com", "完整图落款合影图上传成功");
								AlertUtils
										.setText("正在提交第1个" + poiString + "信息");
								new Thread(micNetworkTask).start();
							} else if (type == TYPE_MIC) {
								int index = data.getInt("index");
								// Log.e("mic" + oi, "图片" + oi + "上传成功");
								if (state.equals("1")) {
									if (index == micMapList.size() - 1) {
										MySharedPreferences
												.getMySharedPreferences(context)
												.setValue(Cache.artIsLoad,
														"yes");
										MySharedPreferences
												.getMySharedPreferences(context)
												.setValue(Cache.ART_ID, art_id);
										// MySharedPreferences
										// .getMySharedPreferences(context)
										// .setValue(Cache.ARTREC_STATUS,
										// "yes");
										System.out.println("开始请求接口3");
										new Thread(comNetworkTask).start();
										// login();
										// comNetwork();
										// comNetwork();
										// MultiPart(uri, null, params,
										// mMicListenerString,
										// mErrorListener, null);
									} else {
										AlertUtils.setText("正在提交第"
												+ (index + 2) + "个" + poiString
												+ "信息");
									}
								} else {
									System.out.println("state=" + state);
								}
							}
							// Intent intent = new Intent(
							// UploadCompleteGraphActivity.this,
							// MicroscopicMapSelectActivity.class);
							// Bundle b = new Bundle();
							// b.putString("state", state);
							// b.putString("art_id", art_id);
							// b.putString("imgUrl",
							// "/storage/emulated/0/zapya/photo/20150127_1033/IMG20141115140855.jpg");
							// intent.putExtras(b);
							// startActivity(intent);
						} else {
							Toast.makeText(
									MicroscopicMapSelectKeepActivity.this,
									jo.optString("msg") + " ", 2).show();
							AlertUtils.dismiss();
						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else {
					Toast.makeText(context, "无响应！", 2).show();
				}
				break;
			case 2:
				int i = (Integer) msg.obj;
				AlertUtils.setProgressBar(i);
				break;
			case -2:
				MySharedPreferences.getMySharedPreferences(context).setValue(
						Cache.artIsLoad, "yes");
				// Toast.makeText(MicroscopicMapSelectActivity.this,
				// "上传成功！", 2).show();
				AlertUtils.dismiss();
				if (Boolean.valueOf(cacheBo)) {
					Intent intent = new Intent(
							MicroscopicMapSelectKeepActivity.this,
							ArtRecordActivity.class);
					startActivity(intent);
				}
				ArtWorkApp.getInstance().artExit();
				break;
			case -1:
				ToastUtil.toast(MicroscopicMapSelectKeepActivity.this,
						"连接超时，请重新请求");
				AlertUtils.dismiss();
				break;
			case 3:
				Bundle bd = msg.getData();
				String req = bd.getString("value");
				// AlertUtils.dismiss();
				if (!TextUtils.isEmpty(req)) {
					Log.i("mylog1", "请求结果为12-->" + req);
					req = req.substring(req.indexOf("{"),
							req.lastIndexOf("}") + 1);
					req = NetUtils.decodeUnicode(req);
					Log.i("mylog2", "请求结果为13-->" + req);
					JSONObject jo;
					try {
						JSONObject json = new JSONObject(req);
						if (json.optString("ret").equals("1")) {
							// String state =
							// jo.optJSONObject("data").optString(
							// "state");
							AlertUtils.setUploadImage(true);

							// Map<String, String> params = new
							// HashMap<String, String>();
							// params.put("token", AppUtil.getUser()
							// .getToken());
							// params.put("art_id", art_id);
							Handler handler1 = new Handler();
							handler1.postDelayed(new Runnable() {
								@Override
								public void run() {
									Message msg = new Message();
									msg.what = -2;
									handler.sendMessage(msg);
								}
							}, 2000);

						} else {
							Toast.makeText(
									MicroscopicMapSelectKeepActivity.this,
									json.optString("msg") + " ", 2).show();
						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else {
					Toast.makeText(context, "无响应！", 2).show();
					AlertUtils.dismiss();
				}
				break;

			default:
				break;
			}

			// TODO
			// UI界面的更新等相关操作
		}
	};

}
